import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;


public class PanelSpelbord extends JPanel {

	private static final long serialVersionUID = 5783398247026685798L;
	JButton[] dropButtons;
	JPanel[][] fields;
	MainWindow mainWindow;

	/**
	 * Create the panel
	 */
	public PanelSpelbord(MainWindow mainWindow, int rows, int columns) {
		super();
		this.mainWindow = mainWindow;
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

		final JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new GridLayout(1, columns));
		buttonPanel.setMaximumSize(new Dimension(1280,100));
		addButtons(buttonPanel, columns);
		add(buttonPanel);

		final JPanel spelbordPanel = new JPanel();
		spelbordPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
		final GridLayout gridLayout = new GridLayout(rows, columns);
		gridLayout.setVgap(4);
		gridLayout.setHgap(4);
		spelbordPanel.setLayout(gridLayout);
		addFields(spelbordPanel, rows, columns);
		add(spelbordPanel);
	}
	
	private void addButtons(JPanel buttonPanel, int nrButtons) {
		// TODO: actie koppelen aan de buttons
		dropButtons = new JButton[nrButtons];
		
		for (int i=0; i<nrButtons; i++)
		{
			dropButtons[i] = new JButton();
			dropButtons[i].setText("Drop");
			dropButtons[i].setName("" + i);
			dropButtons[i].addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                dropButtonActionPerformed(evt);
	            }
	        });
			buttonPanel.add(dropButtons[i]);
		}
	}
	
	private void dropButtonActionPerformed(java.awt.event.ActionEvent evt) {
		JButton button = (JButton) evt.getSource();
		Integer.parseInt(button.getName());
		if (button.isEnabled())
			mainWindow.doMove(Integer.parseInt(button.getName()));		
	}
	
	private void addFields(JPanel spelbordPanel, int nrRows, int nrColumns){
		fields = new JPanel[nrRows][nrColumns];
		
		for (int i=0; i<nrRows; i++)
		{
			for (int j=0; j<nrColumns; j++)
			{
				fields[i][j] = new JPanel();
				fields[i][j].setBorder(new LineBorder(Color.black, 1, false));
				spelbordPanel.add(fields[i][j]);
				
			}
		}		
	}
	
	public void setColorField(int x, int y, Color color) {
		//System.out.println("kleur: " + color);
		fields[x][y].setBackground(color);
		mainWindow.getFrame().validate();
	}

	public void disableButtons() {
		for(int i = 0; i < dropButtons.length; i++)
			dropButtons[i].setEnabled(false);
	}
	
	public void enableButtons() {
		for(int i = 0; i < dropButtons.length; i++)
			dropButtons[i].setEnabled(true);
	}
}
